﻿Imports System.IO

Public Class OneClick
    Dim rowIndexFromMouseDown As Integer
    Dim rw As DataGridViewRow
    Private Structure LoginDetail
        Public ServerName As String
        Public AuthenticationType As String
        Public UserName As String
        Public Password As String
    End Structure

    Dim LoginDetails As New Microsoft.VisualBasic.Collection

    Private Sub OneClick_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        WizardPanel1.StartWizard()
        btnPrevious.Enabled = False

        AddHandler WizardPanel1.OnNextUI, AddressOf WizardPanel1_OnNextUI
        AddHandler WizardPanel1.OnPrevUI, AddressOf WizardPanel1_OnPrevUI
        P1_DG_EnableDisable_ContextMenuItem(False)
        P1_DBListCheckedListBox.Items.Clear()

        'Clipboard.Clear()
    End Sub
    Private Sub WizardPanel1_OnNextUI(ByVal e As WizardControl.OnUIChangeEventArgs)
        'enable previous button
        btnPrevious.Enabled = True

        Select Case e.ActiveUIIndex
            Case 0
                ' Welcome Screen No action required

                If P1_MultiScriptsRadioButton.Checked = False And P1_SingleScriptRadioButton.Checked = False Then

                    MsgBox("Please select script option for deployment or rollback.", MsgBoxStyle.Information Or MsgBoxStyle.OkOnly)
                    P1_MultiScriptsRadioButton.Focus()
                    e.CanMoveNextUI = False
                    Return
                End If

                If P1_MultiScriptsRadioButton.Checked Then
                    P1_lblScriptLable.Text = "Scripts Folder"
                Else
                    P1_lblScriptLable.Text = "Select Script"
                End If

            Case 1
                If Not Validate_P1Screen("") Then
                    e.CanMoveNextUI = False
                    Return
                End If

                Dim i As Integer = P1_DG_BatchFileGrid.Rows.Count

                Do While i > 0
                    If P1_DG_BatchFileGrid.Rows(i - 1).Cells("OnError").Value = "" Then
                        'P3dgScripDBServerGrid.Rows.Remove(P3dgScripDBServerGrid.Rows(i - 1))
                        MsgBox("Please select OnError option", MsgBoxStyle.Information Or MsgBoxStyle.OkOnly)
                        e.CanMoveNextUI = False
                        P1_DG_BatchFileGrid.Rows(i - 1).Cells("OnError").Selected = True
                        'Exit Do
                        Return
                    End If
                    i = i - 1
                Loop

                If e.CanMoveNextUI = True Then
                    ' Display Batch File Script here
                    ' Set a variable to the My Documents path.

                    Dim mydocpath As String = P1BatchFileFolderPathTxtBox.Text
                    i = P1_DG_BatchFileGrid.Rows.Count


                    ' Write the string array to a new file named "WriteLines.txt".
                    Using outputFile As New IO.StreamWriter(mydocpath & Convert.ToString("\Run.bat"))

                        For i = 0 To P1_DG_BatchFileGrid.Rows.Count - 1
                            'Do While i > 0
                            Dim tempS As String = ""
                            Dim sqlCommand As String = ""

                            If P1_DG_BatchFileGrid.Rows(i).Cells("AuthenticationType").Value = "SQL Server Authentication" Then

                                sqlCommand += "sqlcmd -b -S " & P1_DG_BatchFileGrid.Rows(i).Cells("Server").Value & " -U  " & P1_DG_BatchFileGrid.Rows(i).Cells("SQLLogin").Value & " -P " & P1_DG_BatchFileGrid.Rows(i).Cells("SQLPassword").Value & " -i " & My.Settings.ServerScriptFolderLocation _
                                                           & "\" & P1ChangeNumberTextBox.Text.Trim & "\" & P1_DG_BatchFileGrid.Rows(i).Cells("ScriptName").Value & " -d " & P1_DG_BatchFileGrid.Rows(i).Cells("Database").Value & " -o " & My.Settings.ServerScriptLogFolderLocation & "\" & P1ChangeNumberTextBox.Text.Trim & "\" & P1_DG_BatchFileGrid.Rows(i).Cells("ScriptName").Value.ToString.Substring(0, P1_DG_BatchFileGrid.Rows(i).Cells("ScriptName").Value.ToString.Length - 4) & "_" & P1_DG_BatchFileGrid.Rows(i).Cells("Server").Value & "_" & P1_DG_BatchFileGrid.Rows(i).Cells("Database").Value & ".txt"
                            Else
                                sqlCommand += "sqlcmd -b -S " & P1_DG_BatchFileGrid.Rows(i).Cells("Server").Value & " -E  -i " & My.Settings.ServerScriptFolderLocation _
                                                           & "\" & P1ChangeNumberTextBox.Text.Trim & "\" & P1_DG_BatchFileGrid.Rows(i).Cells("ScriptName").Value & " -d " & P1_DG_BatchFileGrid.Rows(i).Cells("Database").Value & " -o " & My.Settings.ServerScriptLogFolderLocation & "\" & P1ChangeNumberTextBox.Text.Trim & "\" & P1_DG_BatchFileGrid.Rows(i).Cells("ScriptName").Value.ToString.Substring(0, P1_DG_BatchFileGrid.Rows(i).Cells("ScriptName").Value.ToString.Length - 4) & "_" & P1_DG_BatchFileGrid.Rows(i).Cells("Server").Value & "_" & P1_DG_BatchFileGrid.Rows(i).Cells("Database").Value & ".txt"
                            End If

                            If P1_DG_BatchFileGrid.Rows(i).Cells("OnError").Value.ToString = "Exit Execution" Then
                                tempS += sqlCommand + vbCrLf + "IF errorlevel 1 GOTO :OnError" + vbCrLf
                               
                            Else
                                tempS += sqlCommand + vbCrLf
                            End If

                            If i = P1_DG_BatchFileGrid.Rows.Count - 1 And P1_DG_BatchFileGrid.Rows(i).Cells("OnError").Value.ToString = "Exit Execution" Then
                                tempS += vbCrLf + "GOTO :Success"
                                tempS += vbCrLf + ":Success " + vbCrLf + "ECHO ALL the scripts deployed successfully!!" + vbCrLf + "pause" + vbCrLf + "Exit /b"
                                tempS += vbCrLf + ":OnError " + vbCrLf + "echo (BUILD FAILED) Error while processing file." + vbCrLf + "pause" + vbCrLf + "Exit /b"
                            End If
                            'For Each line As String In lines
                            outputFile.WriteLine(tempS.ToString)

                            P4BatchScriptRBox.Text += tempS.ToString
                            'i = i - 1
                            'Loop
                        Next i

                        P4FinalMessage.Text = "**************************" & vbCrLf & _
                                              "Change Description : " & vbCrLf & _
                                              "**************************" & vbCrLf & _
                                                "Please note: You would need to create folders as mentioned in below instructions on deployment server." & vbCrLf & _
                                                "1. Copy attached scripts on deployment server into folder : " & My.Settings.ServerScriptFolderLocation & "\" & P1ChangeNumberTextBox.Text.Trim & vbCrLf & _
                                                "2. Copy batch file run.bat into folder : " & My.Settings.ServerScriptFolderLocation & vbCrLf & _
                                                "3. Double click the batch file. " & vbCrLf & _
                                                "4. The script deployment log file would be created in location : " & My.Settings.ServerScriptLogFolderLocation & "\" & P1ChangeNumberTextBox.Text.Trim & vbCrLf & _
                                                "5. Collect the log files attach to e-mail send it back to us. " & vbCrLf & _
                                               "************************************************************************************************************" & vbCrLf & _
                                                "Batch File Location on local computer" & vbCrLf & _
                                               "************************************************************************************************************" & vbCrLf & _
                                                "The batch file is created with above script in folder " & mydocpath & "\Run.bat verify the batch file." & vbCrLf & "Please attach scripts and batch file to CR." & vbCrLf & "Thank you for using this application!" & vbCrLf & _
                                               "************************************************************************************************************"
                    End Using

                End If

                'disable next button
                btnNext.Enabled = False

                'enable finish button
                btnFinish.Enabled = True

                'disable previous button
                btnPrevious.Enabled = False


            Case 2



            Case 3


        End Select
    End Sub

    Private Sub WizardPanel1_OnPrevUI(ByVal e As WizardControl.OnUIChangeEventArgs)
        btnNext.Enabled = True
        btnFinish.Enabled = False

        Select Case e.ActiveUIIndex
            Case 0
            Case 1
                btnPrevious.Enabled = False
            Case 2
            Case 3
        End Select
    End Sub


    Private Sub btnNext_Click(sender As Object, e As EventArgs) Handles btnNext.Click
        WizardPanel1.NextUI()

    End Sub

    Private Sub btnPrevious_Click(sender As Object, e As EventArgs) Handles btnPrevious.Click
        WizardPanel1.PreviosUI()
        btnFinish.Enabled = False
    End Sub

    Private Sub btnFinish_Click(sender As Object, e As EventArgs) Handles btnFinish.Click
        Me.Close()
    End Sub

    Private Sub Panel1_Paint(sender As Object, e As PaintEventArgs) Handles Panel1.Paint

    End Sub

    Private Sub P1_DG_ServerList_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles P1_DG_ServerList.CellContentClick

        If e.RowIndex < 0 Then
            Exit Sub
        End If
        Dim senderGrid = DirectCast(sender, DataGridView)

        If TypeOf senderGrid.Columns(e.ColumnIndex) Is DataGridViewButtonColumn AndAlso
           e.RowIndex >= 0 Then
            'TODO - Button Clicked - Execute Code Here
            Dim frmLoginForm As New LoginForm
            frmLoginForm.txtServerName.Text = P1_DG_ServerList.Rows(e.RowIndex).Cells("ServerName").Value
            frmLoginForm.ShowDialog()

            If frmLoginForm.IsApplyToAll = True Then
                Dim j As Integer = P1_DG_ServerList.Rows.Count
                LoginDetails.Clear()
                Do While j > 0
                    Dim loginifo As LoginDetail
                    loginifo.ServerName = P1_DG_ServerList.Rows(j - 1).Cells("ServerName").Value
                    loginifo.AuthenticationType = frmLoginForm.cmbAuthenticationType.Text
                    loginifo.UserName = frmLoginForm.SQLUserverName
                    loginifo.Password = frmLoginForm.SQLPassword
                    LoginDetails.Add(loginifo, loginifo.ServerName)

                    j = j - 1
                Loop


            Else
                Dim loginifo As LoginDetail

                If LoginDetails.Contains(P1_DG_ServerList.Rows(e.RowIndex).Cells("ServerName").Value) Then
                    LoginDetails.Remove(P1_DG_ServerList.Rows(e.RowIndex).Cells("ServerName").Value)
                End If

                loginifo.ServerName = P1_DG_ServerList.Rows(e.RowIndex).Cells("ServerName").Value
                loginifo.AuthenticationType = frmLoginForm.cmbAuthenticationType.Text
                loginifo.UserName = frmLoginForm.SQLUserverName
                loginifo.Password = frmLoginForm.SQLPassword
                LoginDetails.Add(loginifo, loginifo.ServerName)
            End If


        End If


        If P1_DG_ServerList.Rows(e.RowIndex).Cells("DeleteGridRow").Selected = True Then
            P1_DG_ServerList.Rows(e.RowIndex).Cells("DeleteGridRow").Value = True
        End If


    End Sub

    Private Sub P1_DG_ServerList_MouseClick(sender As Object, e As MouseEventArgs) Handles P1_DG_ServerList.MouseClick
        If e.Button = Windows.Forms.MouseButtons.Right Then

        End If
    End Sub


    Private Sub P1_DG_ServerList_MouseDown(sender As Object, e As MouseEventArgs) Handles P1_DG_ServerList.MouseDown

    End Sub

    Private Sub P1_DG_EnableDisable_ContextMenuItem(ByVal IsEnable As Boolean)


        'SelectRowToolStripMenuItem.Enabled = IsEnable
        PasteToolStripMenuItem.Enabled = IsEnable
        DeleteRowToolStripMenuItem.Enabled = IsEnable
        'ModifyRowToolStripMenuItem.Enabled = IsEnable



        If Clipboard.GetText = "" Then
            PasteToolStripMenuItem.Enabled = False

        Else
            PasteToolStripMenuItem.Enabled = True
        End If

    End Sub

    Private Sub PasteToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles PasteToolStripMenuItem.Click
        On Error Resume Next

        Dim i As Integer = P1_DG_ServerList.Rows.Count

        If i = 0 Then
            'Add Rows
            Dim copiedContent As String = Clipboard.GetText
            For Each row As String In copiedContent.Split(vbNewLine)
                If Not String.IsNullOrEmpty(row) Then
                    'If P1_DG_ServerList.Rows(i).Cells("ServerName").Value <> row Then
                    Dim dgvtbc As DataGridViewTextBoxCell
                    P1_DG_ServerList.Rows.Add()
                    dgvtbc = P1_DG_ServerList.Rows(i).Cells("ServerName")
                    dgvtbc.Value = row

                    P1_DG_ServerList.Rows(i).Cells("DeleteGridRow").Value = False

                    i = i + 1
                    'End If
                End If
            Next
        Else
            'Delete rows first
            Do While i > 0
                ' If Boolean.Parse(P1_DG_BatchFileGrid.Rows(i - 1).Cells("DeleteGridRow").Value.ToString) = True Then
                P1_DG_ServerList.Rows.Remove(P1_DG_ServerList.Rows(i - 1))
                ' End If
                i = i - 1
            Loop
            'Add Rows

            Dim copiedContent As String = Clipboard.GetText
            For Each row As String In copiedContent.Split(vbNewLine)
                If Not String.IsNullOrEmpty(row) Then
                    Dim dgvtbc As DataGridViewTextBoxCell
                    P1_DG_ServerList.Rows.Add()
                    dgvtbc = P1_DG_ServerList.Rows(i).Cells("ServerName")
                    dgvtbc.Value = row

                    P1_DG_ServerList.Rows(i).Cells("DeleteGridRow").Value = False


                    i = i + 1
                End If

            Next

        End If

        RemoveDuplicateRow()
        If LoginDetails.Count > 0 Then
            LoginDetails.Clear()
        End If
        P1_DG_EnableDisable_ContextMenuItem(True)
    End Sub

    Private Sub DeleteRowToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles DeleteRowToolStripMenuItem.Click
        Dim j As Integer = P1_DG_ServerList.Rows.Count

        Dim al As ArrayList = New ArrayList()



        Do While j > 0
            If IsNothing(P1_DG_ServerList.Rows(j - 1).Cells("DeleteGridRow").Value) = True Then
                P1_DG_ServerList.Rows(j - 1).Cells("DeleteGridRow").Value = False
            End If
            If Boolean.Parse(P1_DG_ServerList.Rows(j - 1).Cells("DeleteGridRow").Value.ToString) = True Then

                al.Add(j - 1)
                If LoginDetails.Count > 0 Then
                    LoginDetails.Remove(P1_DG_ServerList.Rows(j - 1).Cells("ServerName").Value)
                End If

            End If
            j = j - 1
        Loop
        'j = 0
        For Each j In al
            ' Console.Write("{0} ", i)
            P1_DG_ServerList.Rows.RemoveAt(j)

        Next j


        '  If P1_DG_ServerList.Rows.Count = 0 Then
        P1_DG_EnableDisable_ContextMenuItem(P1_DG_ServerList.Rows.Count)
        '  End If

    End Sub

    Private Sub P1BrowseClick_Click(sender As Object, e As EventArgs) Handles P1BrowseClick.Click
        If P1_lblScriptLable.Text = "Select Script" Then

            If P1_ScriptOpenFileDialog.ShowDialog <> Windows.Forms.DialogResult.Cancel Then
                P1BrowseTextBox.Text = P1_ScriptOpenFileDialog.FileName
            End If

        Else
            If fbdFinalOutputFolder.ShowDialog() <> Windows.Forms.DialogResult.Cancel Then
                P1BrowseTextBox.Text = fbdFinalOutputFolder.SelectedPath
            End If
        End If

    End Sub


    Private Sub PasteToolStripMenuItem1_Click(sender As Object, e As EventArgs) Handles PasteToolStripMenuItem1.Click

        On Error Resume Next

        P1_DBListCheckedListBox.Items.Clear()

        Dim copiedContent As String = Clipboard.GetText

        For Each row As String In copiedContent.Split(vbNewLine)

            If Not String.IsNullOrEmpty(row) Then
                If P1_DBListCheckedListBox.Items.Contains(row.Trim) = False Then
                    P1_DBListCheckedListBox.Items.Add(row.Trim())
                End If
            End If

        Next
        P1_DBListCheckedListBox.ForeColor = Color.White
    End Sub

    Private Sub DeleteSelectedToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles DeleteSelectedToolStripMenuItem.Click
        Dim count As Integer = P1_DBListCheckedListBox.Items.Count

        For index As Integer = count To 1 Step -1

            If P1_DBListCheckedListBox.CheckedItems.Contains(P1_DBListCheckedListBox.Items(index - 1)) Then
                P1_DBListCheckedListBox.Items.RemoveAt(index - 1)

            End If
        Next
    End Sub



    Private Sub P1_DBListCheckedListBox_SelectedIndexChanged(sender As Object, e As EventArgs) Handles P1_DBListCheckedListBox.SelectedIndexChanged

    End Sub

    Private Sub P1_SelectAllClick_Click(sender As Object, e As EventArgs) Handles P1_SelectAllClick.Click

        Dim j As Integer = P1_DG_ServerList.Rows.Count
        If P1_DG_ServerList.Rows.Count > 0 Then
            Do While j > 0
                P1_DG_ServerList.Rows(j - 1).Cells("DeleteGridRow").Value = True
                j = j - 1
            Loop

        End If
        Try
            P1_DBListCheckedListBox.SelectedItems.Clear()
            For i As Integer = 0 To P1_DBListCheckedListBox.Items.Count - 1
                P1_DBListCheckedListBox.SetItemChecked(i, True)
            Next
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub

    Private Sub P1_RemoveAllClick_Click(sender As Object, e As EventArgs) Handles P1_RemoveAllClick.Click
        Dim j As Integer = P1_DG_ServerList.Rows.Count
        If P1_DG_ServerList.Rows.Count > 0 Then
            Do While j > 0
                P1_DG_ServerList.Rows(j - 1).Cells("DeleteGridRow").Value = False
                j = j - 1
            Loop

        End If
        Try
            P1_DBListCheckedListBox.SelectedItems.Clear()
            For i As Integer = 0 To P1_DBListCheckedListBox.Items.Count - 1
                P1_DBListCheckedListBox.SetItemChecked(i, False)
            Next
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub

    Private Sub P1_AddToBatchFileClick_Click(sender As Object, e As EventArgs) Handles P1_AddToBatchFileClick.Click
        'Validation of fields.

        If Validate_P1Screen("P1_DG_BatchFileGrid") = False Then
            Exit Sub
        End If

        P1_BatchFileDeleteRow.Enabled = P1_DG_BatchFileGrid.Rows.Count
        P1_MoveUpButton.Enabled = P1_DG_BatchFileGrid.Rows.Count
        P1_MoveDownButton.Enabled = P1_DG_BatchFileGrid.Rows.Count

        'P1_DG_BatchFileGrid.SelectedRows(0).Selected = False

        If P1_lblScriptLable.Text = "Select Script" Then


            Dim i As Integer = P1_DG_BatchFileGrid.Rows.Count

            ' Loop through and display each path.
            For j As Integer = 0 To P1_DG_ServerList.Rows.Count - 1
                If Boolean.Parse(P1_DG_ServerList.Rows(j).Cells("DeleteGridRow").Value.ToString) = True Then
                    For k As Integer = 0 To P1_DBListCheckedListBox.Items.Count - 1
                        If P1_DBListCheckedListBox.CheckedItems.Contains(P1_DBListCheckedListBox.Items(k)) Then

                            Dim dgvtbc As DataGridViewTextBoxCell
                            P1_DG_BatchFileGrid.Rows.Add()
                            Dim fi As New IO.FileInfo(P1BrowseTextBox.Text)

                            dgvtbc = P1_DG_BatchFileGrid.Rows(i).Cells("ScriptLocation")
                            dgvtbc.Value = fi.DirectoryName

                            dgvtbc = P1_DG_BatchFileGrid.Rows(i).Cells("ScriptName")
                            dgvtbc.Value = fi.Name

                            Dim LD As LoginDetail
                            If LoginDetails.Count > 0 Then
                                LD = LoginDetails.Item(P1_DG_ServerList.Rows(j).Cells("ServerName").Value)

                                If LD.AuthenticationType = "Windows Authentication" Then
                                    dgvtbc = P1_DG_BatchFileGrid.Rows(i).Cells("AuthenticationType")
                                    'Windows Authentication
                                    'SQL Server Authentication
                                    dgvtbc.Value = "Windows Authentication"
                                    dgvtbc = P1_DG_BatchFileGrid.Rows(i).Cells("SQLLogin")
                                    dgvtbc.Value = "E"

                                    dgvtbc = P1_DG_BatchFileGrid.Rows(i).Cells("SQLPassword")
                                    dgvtbc.Value = ""
                                Else
                                    dgvtbc = P1_DG_BatchFileGrid.Rows(i).Cells("AuthenticationType")
                                    dgvtbc.Value = "SQL Server Authentication"
                                    dgvtbc = P1_DG_BatchFileGrid.Rows(i).Cells("SQLLogin")
                                    dgvtbc.Value = LD.UserName

                                    dgvtbc = P1_DG_BatchFileGrid.Rows(i).Cells("SQLPassword")
                                    dgvtbc.Value = LD.Password
                                End If
                            End If
                            dgvtbc = P1_DG_BatchFileGrid.Rows(i).Cells("Server")
                            dgvtbc.Value = P1_DG_ServerList.Rows(j).Cells("ServerName").Value.ToString

                            dgvtbc = P1_DG_BatchFileGrid.Rows(i).Cells("Database")
                            dgvtbc.Value = P1_DBListCheckedListBox.Items(k)

                            P1_DG_BatchFileGrid.Rows(i).Cells("SelectRow").Value = False
                            P1_DG_BatchFileGrid.Rows(i).Cells("OnError").Value = "Exit Execution"

                            i = i + 1
                        End If
                    Next
                End If
            Next

        Else
            Dim list As List(Of String) = GetFilesRecursive(P1BrowseTextBox.Text)

            Dim i As Integer = P1_DG_BatchFileGrid.Rows.Count
            For Each path In list
                ' Loop through and display each path.
                For j As Integer = 0 To P1_DG_ServerList.Rows.Count - 1
                    If Boolean.Parse(P1_DG_ServerList.Rows(j).Cells("DeleteGridRow").Value.ToString) = True Then
                        For k As Integer = 0 To P1_DBListCheckedListBox.Items.Count - 1
                            If P1_DBListCheckedListBox.CheckedItems.Contains(P1_DBListCheckedListBox.Items(k)) Then

                                Dim dgvtbc As DataGridViewTextBoxCell
                                P1_DG_BatchFileGrid.Rows.Add()
                                'Dim fi As New IO.FileInfo(P1BrowseTextBox.Text)

                                dgvtbc = P1_DG_BatchFileGrid.Rows(i).Cells("ScriptLocation")
                                dgvtbc.Value = P1BrowseTextBox.Text

                                dgvtbc = P1_DG_BatchFileGrid.Rows(i).Cells("ScriptName")
                                dgvtbc.Value = System.IO.Path.GetFileName(path)

                                Dim LD As LoginDetail
                                If LoginDetails.Count > 0 Then
                                    LD = LoginDetails.Item(P1_DG_ServerList.Rows(j).Cells("ServerName").Value)

                                    If LD.AuthenticationType = "Windows Authentication" Then
                                        dgvtbc = P1_DG_BatchFileGrid.Rows(i).Cells("AuthenticationType")
                                        'Windows Authentication
                                        'SQL Server Authentication
                                        dgvtbc.Value = "Windows Authentication"
                                        dgvtbc = P1_DG_BatchFileGrid.Rows(i).Cells("SQLLogin")
                                        dgvtbc.Value = "E"

                                        dgvtbc = P1_DG_BatchFileGrid.Rows(i).Cells("SQLPassword")
                                        dgvtbc.Value = ""
                                    Else
                                        dgvtbc = P1_DG_BatchFileGrid.Rows(i).Cells("AuthenticationType")
                                        dgvtbc.Value = "SQL Server Authentication"
                                        dgvtbc = P1_DG_BatchFileGrid.Rows(i).Cells("SQLLogin")
                                        dgvtbc.Value = LD.UserName

                                        dgvtbc = P1_DG_BatchFileGrid.Rows(i).Cells("SQLPassword")
                                        dgvtbc.Value = LD.Password
                                    End If
                                End If
                                dgvtbc = P1_DG_BatchFileGrid.Rows(i).Cells("Server")
                                dgvtbc.Value = P1_DG_ServerList.Rows(j).Cells("ServerName").Value.ToString

                                dgvtbc = P1_DG_BatchFileGrid.Rows(i).Cells("Database")
                                dgvtbc.Value = P1_DBListCheckedListBox.Items(k)

                                P1_DG_BatchFileGrid.Rows(i).Cells("SelectRow").Value = False
                                P1_DG_BatchFileGrid.Rows(i).Cells("OnError").Value = "Exit Execution"

                                i = i + 1
                            End If
                        Next
                    End If
                Next
            Next
        End If

        P1_BatchFileDeleteRow.Enabled = P1_DG_BatchFileGrid.Rows.Count
        P1_MoveUpButton.Enabled = P1_DG_BatchFileGrid.Rows.Count
        P1_MoveDownButton.Enabled = P1_DG_BatchFileGrid.Rows.Count


    End Sub

    Private Function GetFilesRecursive(ByVal initial As String) As List(Of String)
        ' This list stores the results.
        Dim result As New List(Of String)

        ' This stack stores the directories to process.
        Dim stack As New Stack(Of String)

        ' Add the initial directory
        stack.Push(initial)

        ' Continue processing for each stacked directory
        Do While (stack.Count > 0)
            ' Get top directory string
            Dim dir As String = stack.Pop
            Try
                ' Add all immediate file paths
                result.AddRange(Directory.GetFiles(dir, "*.sql"))

                ' Loop through all subdirectories and add them to the stack.
                Dim directoryName As String
                For Each directoryName In Directory.GetDirectories(dir)
                    stack.Push(directoryName)
                Next

            Catch ex As Exception
            End Try
        Loop

        ' Return the list
        Return result
    End Function
    Private Sub RemoveDuplicateRow()
        On Error Resume Next
        Dim al As Collection = New Collection()


        For i As Integer = 0 To Me.P1_DG_ServerList.RowCount - 1
            Dim count As Integer = 1
            For j As Integer = 0 To Me.P1_DG_ServerList.RowCount - 1

                If String.Compare(P1_DG_ServerList.Rows(i).Cells(1).Value.ToString.Trim, P1_DG_ServerList.Rows(j).Cells(1).Value.ToString.Trim, False) = 0 And i <> j Then
                    If count = 1 Then
                        al.Add(P1_DG_ServerList.Rows(i).Cells(1).Value.ToString.Trim, P1_DG_ServerList.Rows(i).Cells(1).Value.ToString.Trim)
                    End If
                    count = count + 1
                End If
            Next
            If count = 1 Then
                al.Add(P1_DG_ServerList.Rows(i).Cells(1).Value.ToString.Trim, P1_DG_ServerList.Rows(i).Cells(1).Value.ToString.Trim)
            End If
        Next

        On Error GoTo 0

        P1_DG_ServerList.Rows.Clear()

        For i = 0 To al.Count - 1
            Dim dgvtbc As DataGridViewTextBoxCell
            P1_DG_ServerList.Rows.Add()
            dgvtbc = P1_DG_ServerList.Rows(i).Cells("ServerName")
            dgvtbc.Value = al.Item(i + 1)
            P1_DG_ServerList.Rows(i).Cells("DeleteGridRow").Value = False

        Next

    End Sub

    Private Function Validate_P1Screen(Optional ExcludeControlName As String = "P1_DG_BatchFileGrid") As Boolean

        If ExcludeControlName = "" Then


            If P1ChangeNumberTextBox.Text = String.Empty Then
                MsgBox("Please enter change number for deployment.", MsgBoxStyle.Information Or MsgBoxStyle.OkOnly)
                P1ChangeNumberTextBox.Focus()
                Validate_P1Screen = False
                Exit Function
            End If

            If P1BrowseTextBox.Text = String.Empty Then
                MsgBox("Please select script for deployment or rollback.", MsgBoxStyle.Information Or MsgBoxStyle.OkOnly)
                P1BrowseClick.Focus()
                Validate_P1Screen = False
                Exit Function
            End If

            If P1_DG_ServerList.Rows.Count = 0 Then
                MsgBox("Please paste server list involve in deployment or rollback.", MsgBoxStyle.Information Or MsgBoxStyle.OkOnly)
                Validate_P1Screen = False
                Exit Function
            End If

            If P1_DBListCheckedListBox.Items.Count = 0 Then
                MsgBox("Please paste Database list involve in deployment or rollback.", MsgBoxStyle.Information Or MsgBoxStyle.OkOnly)
                Validate_P1Screen = False
                Exit Function
            End If


            If P1_DG_BatchFileGrid.Rows.Count = 0 Then
                MsgBox("Please add script + server + database list involve in deployment or rollback.", MsgBoxStyle.Information Or MsgBoxStyle.OkOnly)
                P1_AddToBatchFileClick.Focus()
                Validate_P1Screen = False
                Exit Function
            End If

            If P1BatchFileFolderPathTxtBox.Text = String.Empty Then
                MsgBox("Please select folder location where you want save batch file.", MsgBoxStyle.Information Or MsgBoxStyle.OkOnly)
                P1BatchFileBrowseClick.Focus()
                Validate_P1Screen = False
                Exit Function
            End If


            If LoginDetails.Count = 0 Then
                MsgBox("Please update server authentication method by clicking button on server list.", MsgBoxStyle.Information Or MsgBoxStyle.OkOnly)
                Validate_P1Screen = False
                Exit Function
            End If

        Else
            If P1ChangeNumberTextBox.Text = String.Empty And ExcludeControlName <> "P1ChangeNumberTextBox" Then
                MsgBox("Please enter change number for deployment.", MsgBoxStyle.Information Or MsgBoxStyle.OkOnly)
                P1ChangeNumberTextBox.Focus()
                Validate_P1Screen = False
                Exit Function
            End If

            If P1BrowseTextBox.Text = String.Empty And ExcludeControlName <> "P1BrowseTextBox" Then
                MsgBox("Please select script for deployment or rollback.", MsgBoxStyle.Information Or MsgBoxStyle.OkOnly)
                P1BrowseClick.Focus()
                Validate_P1Screen = False
                Exit Function
            End If

            If P1_DG_ServerList.Rows.Count = 0 And ExcludeControlName <> "P1_DG_ServerList" Then
                MsgBox("Please paste server list involve in deployment or rollback.", MsgBoxStyle.Information Or MsgBoxStyle.OkOnly)
                Validate_P1Screen = False
                Exit Function
            End If

            If P1_DBListCheckedListBox.Items.Count = 0 And ExcludeControlName <> "P1_DBListCheckedListBox" Then
                MsgBox("Please paste Database list involve in deployment or rollback.", MsgBoxStyle.Information Or MsgBoxStyle.OkOnly)
                Validate_P1Screen = False
                Exit Function
            End If


            If P1_DG_BatchFileGrid.Rows.Count = 0 And ExcludeControlName <> "P1_DG_BatchFileGrid" Then
                MsgBox("Please add script + server + database list involve in deployment or rollback.", MsgBoxStyle.Information Or MsgBoxStyle.OkOnly)
                P1_AddToBatchFileClick.Focus()
                Validate_P1Screen = False
                Exit Function
            End If

            If P1BatchFileFolderPathTxtBox.Text = String.Empty And ExcludeControlName <> "P1BatchFileFolderPathTxtBox" Then
                MsgBox("Please select folder location where you want save batch file.", MsgBoxStyle.Information Or MsgBoxStyle.OkOnly)
                P1BatchFileBrowseClick.Focus()
                Validate_P1Screen = False
                Exit Function
            End If

            If LoginDetails.Count = 0 Then
                MsgBox("Please update server authentication method by clicking button on server list.", MsgBoxStyle.Information Or MsgBoxStyle.OkOnly)
                Validate_P1Screen = False
                Exit Function
            End If
        End If
        Return True
    End Function

    Private Sub P1_BatchFileDeleteRow_Click(sender As Object, e As EventArgs) Handles P1_BatchFileDeleteRow.Click
        Dim i As Integer = P1_DG_BatchFileGrid.Rows.Count

        Do While i > 0
            If Boolean.Parse(P1_DG_BatchFileGrid.Rows(i - 1).Cells("SelectRow").Value.ToString) = True Then
                P1_DG_BatchFileGrid.Rows.Remove(P1_DG_BatchFileGrid.Rows(i - 1))
            End If
            i = i - 1
        Loop

        P1_BatchFileDeleteRow.Enabled = P1_DG_BatchFileGrid.Rows.Count
        P1_MoveUpButton.Enabled = P1_DG_BatchFileGrid.Rows.Count
        P1_MoveDownButton.Enabled = P1_DG_BatchFileGrid.Rows.Count
    End Sub

    Private Sub P1_MoveUpButton_Click(sender As Object, e As EventArgs) Handles P1_MoveUpButton.Click
        If Me.P1_DG_BatchFileGrid.CurrentCell.RowIndex = 0 Then

            Exit Sub

        End If

        MoveRow(-1) ' move up in the datagridview (row index is 1 less)
    End Sub

    Private Sub MoveRow(ByVal i As Integer)

        Try



            If (Me.P1_DG_BatchFileGrid.SelectedCells.Count > 0) Then

                Dim curr_index As Integer = Me.P1_DG_BatchFileGrid.CurrentCell.RowIndex

                Dim curr_col_index As Integer = Me.P1_DG_BatchFileGrid.CurrentCell.ColumnIndex

                Dim curr_row As DataGridViewRow = Me.P1_DG_BatchFileGrid.CurrentRow

                If (curr_index = Me.P1_DG_BatchFileGrid.RowCount - 1 And i = 1) Or (curr_index = 0 And i = -1) Then Exit Sub

                Me.P1_DG_BatchFileGrid.Rows.Remove(curr_row)

                Me.P1_DG_BatchFileGrid.Rows.Insert(curr_index + i, curr_row)

                Me.P1_DG_BatchFileGrid.CurrentCell = Me.P1_DG_BatchFileGrid(curr_col_index, curr_index + i)

            End If

        Catch ex As Exception

            ' do nothing if error encountered while trying to move the row up or down

        End Try

    End Sub



    Private Sub P1_MoveDownButton_Click(sender As Object, e As EventArgs) Handles P1_MoveDownButton.Click
        'If already on the bottom row, don’t try to move the row down

        If Me.P1_DG_BatchFileGrid.CurrentCell.RowIndex = Me.P1_DG_BatchFileGrid.RowCount - 1 Then

            Exit Sub

        End If
        ' move down in the data grid view (row index is 1 more)
        MoveRow(1)
    End Sub

    Private Sub P1BatchFileBrowseClick_Click(sender As Object, e As EventArgs) Handles P1BatchFileBrowseClick.Click
        If fbdFinalOutputFolder.ShowDialog() <> Windows.Forms.DialogResult.Cancel Then
            P1BatchFileFolderPathTxtBox.Text = fbdFinalOutputFolder.SelectedPath
        End If
    End Sub


End Class
